import { ColorExtraction } from "@/utils/ColorExtraction.js";
import { Window_Selectable } from "@/windows/Window_Selectable.js";

export class Window_EquipSlot extends Window_Selectable {
    constructor(width,height) {
        super(width,height,false);
        this.init(width,height);
    }

    init(width, height) {
        this._actor = null;
        this._list=[];
        this.okHandler=null;
        this.cancelHandler=null;
        this.changedHandler=null;
        super.init(width,height);
    }

    destroy(opts){
        super.destroy(opts);
        this._actor = null;
        this._list.length=0;
        this.okHandler=null;
        this.cancelHandler=null;
        this.changedHandler=null;
    }

    slotIndex(){
        return this.selectedIndex;
    }

    setActor(actor) {
        if (this._actor !== actor) {
            this._actor = actor;
            this.refresh();
        }
    }

    setHandler(name,callback){
        if(name=='ok'){
            this.okHandler=callback;
        }else if(name=='cancel'){
            this.cancelHandler=callback;
        }else if(name=='changed'){
            this.changedHandler=callback;
        }
    }

    row(){return this.length();}
    viewRow(){return Math.floor(this.contentsHeight()/this.itemHeight());}
    length() {return this._actor?.equipSlots().length??0;}

    drawItem(index,x,y,width,height) {
        this.changeTextColor(ColorExtraction.systemColor());
        let enabled=this.itemEnabled(index);
        if(!enabled){
            this.changePaintOpacity(false);
        }
        this.drawText(this.slotName(index), x, y, width,height);
        let gameEquip=this._actor._equips[index];
        this.drawItemName(gameEquip?.object(), x + 138, y,width-138);
        if(!enabled){
            this.changePaintOpacity(true);
        }
    }

    slotName(index) {
        let etypeId = this._actor?.equipSlots()[index];
        return $dataSystem.equipTypes[etypeId]??'';
    }

    itemEnabled(index) {
        return super.itemEnabled(index)&&this._actor?.isEquipChangeOk(index);
    }

    makeItemList(){
        if(this._actor){
            this._list=this._actor.equipSlots();
        }else{
            this._list.length=0;
        }
    }

    refresh(){
        this.makeItemList();
        super.refresh();
    }

    onResponse(index){
        this.okHandler?.(this._list[index],index);
    }

    onSelectChanged(index,oldIndex){
        this.changedHandler?.(this._list[index],this._list[oldIndex]);
    }

    onCancel(){
        this.cancelHandler?.();
    }
}